package StudyCode.summary.myfile;

import java.io.IOException;
import java.nio.file.*;
import java.util.concurrent.TimeUnit;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class UsingWatchServiceSubscribeFolderChange {
	public static void main(String[] args) {
		try {
			System.out.println("监听事件, 按 q<Enter> 退出");
			FileSystem fileSystem = FileSystems.getDefault();
			WatchService service = fileSystem.newWatchService();
			Path path = fileSystem.getPath(".");
			System.out.println("监听 :" + path.toAbsolutePath());
			path.register(service, StandardWatchEventKinds.ENTRY_CREATE,
					StandardWatchEventKinds.ENTRY_DELETE,
					StandardWatchEventKinds.ENTRY_MODIFY);
			boolean shouldContinue = true;
			while (shouldContinue) {
				WatchKey key = service.poll(250, TimeUnit.MILLISECONDS);
				while (System.in.available() > 0) {
					int readChar = System.in.read();
					if ((readChar == 'q') || (readChar == 'Q')) {
						shouldContinue = false;
						break;
					}
				}
				if (key == null)
					continue;
				key.pollEvents()
						.stream()
						.filter(
								(event) -> !(event.kind() == StandardWatchEventKinds.OVERFLOW))
						.map((event) -> (WatchEvent<Path>) event)
						.forEach(
								(ev) -> {
									Path filename = ev.context();
									System.out.println("监听到事件 :" + filename.toString()
											+ " " + ev.kind());
								});
				boolean valid = key.reset();
				if (!valid) {
					break;
				}
			}
		} catch (IOException | InterruptedException e) {
			e.printStackTrace();
		}
	}
}
